package controllers;

import javax.persistence.EntityManager;

import models.domain.Address;
import models.domain.Customer;
import models.persistence.JPAUtil;
import play.data.Form;
import play.db.jpa.Transactional;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.login;
import views.html.register;
import controllers.service.CustomerService;

public class Register extends Controller {

	// -Register
	public static class RegisterForm {
		public String username;
		public String password;
		public String taxIdentificationId;
		public String firstName;
		public String lastName;
		public String e_mail;
		public String identificationId;
		public String street;
		public String number;
		public String zipCode;
	}

	@Transactional
	public static Result register() {
		return ok(views.html.register.render());
	}

	@Transactional
	public static Result startRegister() {
		CustomerService customerServive = new CustomerService();

		Form<RegisterForm> registerForm = Form.form(RegisterForm.class)
				.bindFromRequest();
		
		// Validating customer Data
		if (customerServive.validateData(
				registerForm.get().taxIdentificationId,
				registerForm.get().e_mail) == false) {

			models.domain.User user = new models.domain.User(
					registerForm.get().username, registerForm.get().password,
					false);
			Address address = new Address(registerForm.get().street,
					registerForm.get().number, registerForm.get().zipCode);
			// New Customer
			Customer customer = new Customer(
					registerForm.get().taxIdentificationId,
					registerForm.get().firstName, registerForm.get().lastName,
					registerForm.get().e_mail,
					registerForm.get().identificationId, address, user, null);
			//customerServive.StartRegisterProcess(customer);

			EntityManager em=JPAUtil.getCurrentEntityManager();
			 em.persist(customer);
			return ok(login.render());
		} else {
			return ok(register.render());
		}

	}
}
